【security】spring security放行不生效,security放行后还是被拦截,路径变成了/error,security匿名用户无法访问

您所在的位置:网站首页 spring security 拦截器 【security】spring security放行不生效,security放行后还是被拦截,路径变成了/error,security匿名用户无法访问

【security】spring security放行不生效,security放行后还是被拦截,路径变成了/error,security匿名用户无法访问

2024-07-11 13:29| 来源: 网络整理| 查看: 265

文章目录 security最初的配置初步改进后的配置排查真实原因更加合理的配置security放行不生效的另一种情况:匿名用户访问失败 之前写了篇关于security认证的文章 感觉对security了解多了一点,直到遇到过滤器层面的问题,才明白security终究还是那个复杂的security。

security最初的配置 @Configuration public class SecuritySecureConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 登录成功处理类 SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successHandler.setTargetUrlParameter("redirectTo"); http.authorizeRequests() //静态文件允许访问 .antMatchers().permitAll() // 放行 .antMatchers( "/assets/**","/login","/test/**","/testfather/**","/testes/**","/advice/**","css/**","/js/**","/image/*").permitAll() //其他所有请求需要登录, anyRequest 不能配置在 antMatchers 前面 .anyRequest().authenticated() .and() //登录页面配置,用于替换security默认页面 .formLogin().loginPage( "/login").successHandler(successHandler).and() //登出页面配置,用于替换security默认页面 .logout().logoutUrl( "/logout").and() .httpBasic().and() .csrf() .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .ignoringAntMatchers( "/instances", "/actuator/**" ); } }

情况描述: test对应的controller get请求的接口可以访问,但是put,delete 等其它请求无法访问 这个无法访问表现形式和日志级别有关,如果日志级别开的是error 那表现形式就是接口打断点无法进入,控制台无任何报错, postman接口返回的是401 在这里插入图片描述 如果日志级别开的是debug 那么会报错 access is define

初步改进后的配置

在该类中新增一个方法 发现新增后 除了get请求 其它请求也能访问了 问题解决。

后面经过查询得知WebSecurity 和 HttpSecurity 的区别: WebSecurity不走过滤链 通俗的说 不经过各种复杂的filter 直接就放行了 而HttpSecurity 是会经过各种filter的。 在我之前的security认证的那篇博客中有举例 /login 就是典型的走过滤链的接口

/** * configure(WebSecurity web)不走过滤链的放行 * 即不通过security 完全对外的/最大级别的放行 **/ @Override public void configure(WebSecurity web) throws Exception { // 直接放行了 如果是login接口 必须通过HttpSecurity 走过滤链 因为登录涉及 SecurityContextHolder web.ignoring().antMatchers("/test/**","/testfather/**","/testes/**"); } 排查真实原因

经过上面的操作后 问题是解决了 而且其实有些我们自己写的接口(如/test/**) 确实可以不需要经过过滤链,但是疑惑还在 .antMatchers( " ”).permitAll() 印象中都是这么放行的,那为什么就出现了get被放行 , put,delete等方法被拦截呢?

下面复盘排查步骤:

开始分析与调试: 被拦截说明放行失败,说明antMatchers方法路径匹配可能出现问题,那我们先跟进去看 最终跟到的方法是 AntPathRequestMatcher 类中的public boolean matches(HttpServletRequest request) 方法 public boolean matches(HttpServletRequest request) { //默认会调用antMatchers(null,"/test/**/)就是说我们没有传httpMethod // httpMethod 为null 不走该判断 if (this.httpMethod != null && StringUtils.hasText(request.getMethod()) && this.httpMethod != valueOf(request.getMethod())) { if (logger.isDebugEnabled()) { logger.debug("Request '" + request.getMethod() + " " + this.getRequestPath(request) + "' doesn't match '" + this.httpMethod + " " + this.pattern + "'"); } return false; // 如果antMatchers(/**)全部放行 // 也不走该判断 } else if (this.pattern.equals("/**")) { if (logger.isDebugEnabled()) { logger.debug("Request '" + this.getRequestPath(request) + "' matched by universal pattern '/**'"); } return true; } else { // 核心就是这儿了 获取url 用于比较 String url = this.getRequestPath(request); if (logger.isDebugEnabled()) { logger.debug("Checking match of request : '" + url + "'; against '" + this.pattern + "'"); } // 去比较url和antMatchers里面的pattern return this.matcher.matches(url); } }

按理来说我们发起的请求是什么 那url就是什么 当debug的时候 意外的发现了是/error 当路径没找到的时候 会重定向到/error 那第一阶段的原因是明白了 路径变成了/error 所以匹配不上 没有放行。

继续观察debug级别的日志 所以不得不说 debug级别的日志 在很多时候是有作用的 即使在开发中也不应该简单粗暴的调成error 在这里插入图片描述 /testes/idx 是我发起请求的url 可以发现 经过Checking match of request : ‘/testes/idx’; against ‘/instances’和’/actuator/**’ 之后 出现了一行 Invalid CSRF token found for , 再接下来 路径就变成了/error ,那么问题就出在这儿了。

通过查阅资料后得知 security防御csrf攻击的方法 写在org.springframework.security.web.csrf路径下的CsrfFilter类

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { request.setAttribute(HttpServletResponse.class.getName(), response); CsrfToken csrfToken = this.tokenRepository.loadToken(request); boolean missingToken = csrfToken == null; if (missingToken) { csrfToken = this.tokenRepository.generateToken(request); this.tokenRepository.saveToken(csrfToken, request, response); } request.setAttribute(CsrfToken.class.getName(), csrfToken); request.setAttribute(csrfToken.getParameterName(), csrfToken); /** private DefaultRequiresCsrfMatcher() { this.allowedMethods = new HashSet(Arrays.asList( "GET", "HEAD", "TRACE", "OPTIONS" )); } **/ // 可以看到除了 "GET", "HEAD", "TRACE", "OPTIONS" 四种方式 其它请求都会被拦截 if (!this.requireCsrfProtectionMatcher.matches(request)) { filterChain.doFilter(request, response); } else { // 其它请求 没有token会被拦截 String actualToken = request.getHeader(csrfToken.getHeaderName()); if (actualToken == null) { actualToken = request.getParameter(csrfToken.getParameterName()); } if (!csrfToken.getToken().equals(actualToken)) { if (this.logger.isDebugEnabled()) { // 我们在控制台看到的输出 this.logger.debug("Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request)); } if (missingToken) { this.accessDeniedHandler.handle(request, response, new MissingCsrfTokenException(actualToken)); } else { this.accessDeniedHandler.handle(request, response, new InvalidCsrfTokenException(csrfToken, actualToken)); } } else { filterChain.doFilter(request, response); } } }

这就是为什么我们get请求可以访问 而put,delete等请求失败的原因。

更加合理的配置 @Configuration public class SecuritySecureConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 登录成功处理类 SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successHandler.setTargetUrlParameter("redirectTo"); http.authorizeRequests() //静态文件允许访问 .antMatchers().permitAll() // 放行 .antMatchers( "/assets/**","/login","/test/**","/testfather/**","/testes/**","/advice/**","css/**","/js/**","/image/*").permitAll() //其他所有请求需要登录, anyRequest 不能配置在 antMatchers 前面 .anyRequest().authenticated() .and() //登录页面配置,用于替换security默认页面 .formLogin().loginPage( "/login").successHandler(successHandler).and() //登出页面配置,用于替换security默认页面 .logout().logoutUrl( "/logout").and() .httpBasic().and() // 开启了csrf防御 如果要放行/test/** 还需要在下面ignoringAntMatchers进行配置 .csrf() .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // 这里还需要放行 当然如果是 .csrf().disable()就不会有这个问题了 .ignoringAntMatchers( "/instances", "/actuator/**", "/test/**", "/advice/**", "/testes/**" ); } }

为什么有的项目没有ignoringAntMatchers配置也放行成功了呢? 因为那些项目 很可能直接.csrf().disable() 所以不会出现该问题

题外话: 想必可能有同学听过 controller层接口必须捕获异常 ,如果不捕获 其中坑点之一就和这个security框架的.csrf()有关:

* 异常没有捕获 ==》 * 如果当开启了 csrf 且又没有放行时 (在 WebSecurity 放行了 否则进不来接口) 异常会抛到 security 导致security报错(同样需要debug级别日志查看 error看不到) 且返回401 * 换句话说:WebSecurity放行的方式 还需配合接口的try catch 否则接口报错了 也会返回401 * 当然 其它情况可能也会因为异常没捕获 而造成未知结果 * 所以我们还是应该遵循规范:接口必须异常捕获 security放行不生效的另一种情况:匿名用户访问失败

这里有个小知识点 permitAll() 包含登录用户、匿名用户,而anonymous()是匿名用户才能访问。

最近又遇到一个新的坑,抛出了AccessDeniedException异常 我们上文提到了 public void configure(WebSecurity web) 放行是不走security的, 那如果我们必须要走security,我们没有开启csrf防御 ,也设置了permitAll() 为什么还是放行失败呢?

如下面的代码

protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/public/**","/common/**", "/tool/**", "/upload/**","/download/**").permitAll() .anyRequest().authenticated() .and() .csrf().disable() .formLogin().disable() .cors() .and() .logout() .addLogoutHandler(tokenClearLogoutHandler()) .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandlerImpl()); // 下面代码中 添加了自定义过滤器 http .addFilterBefore(new DynamicallyUrlInterceptor(), FilterSecurityInterceptor.class) .addFilter(new JWTAuthorizationFilter(authenticationManager(), jwtTokenService, requestLogApplication)) .addFilter(new JWTAuthenticationFilter(authenticationManager(),cacheApplicationService)) .exceptionHandling() .authenticationEntryPoint(myAuthenticationEntryPoint) ; }

问题就出在自定义过滤器, 这里就不贴代码了 主要就是因为自定义代码里面做了拦截 这里说一下思路:

找到项目中直接或间接实现 FilterInvocationSecurityMetadataSource 或 SecurityMetadataSource 接口的类, (FilterInvocationSecurityMetadataSource 接口继承 SecurityMetadataSource接口 ) 在这里插入图片描述

在这里插入图片描述

并找到 getAttributes 方法的实现

Collection getAttributes(Object object) throws IllegalArgumentException;

最后return的结果 都是调用 SecurityConfig.createListFromCommaDelimitedString()或SecurityConfig.createList()方法 这个方法就是往里面写入可访问的角色,在自定义的时候 把匿名用户角色漏了 就会出现无法访问的情况 我们将 “ROLE_ANONYMOUS” 写进去就能访问了



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3